﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using backfile.util;
using System.Collections;
using System.Data;

namespace backfile.job
{
    class BackUp 
    {
        public static int run(Dictionary<string, string> task)
        {
            
            string source_dir = task["source_dir"];
            string target_dir = task["target_dir"];
            string title = task["title"];
            string interval = task["interval"];
            string is_compress = task["is_compress"];
            string is_delete = task["is_delete"];
            string ignore_file = task["ignore_file"];
            string start_date = task["start_date"];
            string next_date = task["next_date"];
            string id = task["id"];

          
            MainForm.instance.ReadMainLog("执行ID:" + id + "，标题：" + title + "任务");

            if (string.IsNullOrEmpty(source_dir))
            {
                MainForm.instance.ReadMainLog("未获取源目录:"+ source_dir);
                updateTaskState(id, next_date, title, interval);
                return 0;
            }
            if (string.IsNullOrEmpty(target_dir))
            {

                MainForm.instance.ReadMainLog("未获取目标目录:"+ target_dir);

                updateTaskState(id, next_date, title, interval);
                return 0;
            }

            if (!FileUtil.IsExistDirectory(source_dir))
            {
                MainForm.instance.ReadMainLog("未找到源目录路径:"+ source_dir);
                updateTaskState(id, next_date, title, interval);
                return 0;
            }
            string ignore = "";
            if (ignore_file.Length > 0)
            {
                ignore = ignore_file.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
                //string[] ignore = ignore_file.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            }

            ZipHelper zip = new ZipHelper();
            Hashtable ht = zip.GetAllFies(source_dir);
            int copy_total = 0;
            int compress_total = 0;
            int delete_total = 0;
            foreach (string key in ht.Keys)
            {
                //Console.WriteLine("file = " + System.IO.Path.GetFileName(key) +",ig="+ignore.IndexOf(System.IO.Path.GetFileName(key)).ToString());
                if (ignore.IndexOf(System.IO.Path.GetFileName(key)) > -1)
                {
                    continue;
                }    
                if (is_compress == "是")
                {
                    string aFirstName = key.Substring(key.LastIndexOf("\\") + 1, (key.LastIndexOf(".") - key.LastIndexOf("\\") - 1));
                    string file = target_dir + "\\" + aFirstName + ".zip";
                    zip.ZipFile(key, file);
                    compress_total++;
                }
                else
                {
                    string file = target_dir + "\\" + FileUtil.GetFileName(key);
                    FileUtil.Copy(key, file);
                    copy_total++;
                }

                if (is_delete == "是")
                {
                    FileUtil.DeleteFile(key);
                    delete_total++;
                }
            }


            updateTaskState(id,next_date,title, interval);
            MainForm.instance.ReadMainLog("ID:" + id + "，标题：" + title + "任务共压缩文件："+ compress_total+"，共复制文件："+ copy_total+"，共删除文件："+ delete_total);

            return 1;
        }

        private static void updateTaskState(string id,string start_date,string title,string interval)
        {
            start_date = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
            DateTime st = Convert.ToDateTime(start_date);
            string next_date = st.AddSeconds(Convert.ToInt32(interval)).ToString("yyyy-MM-dd HH:mm:ss");

            string sql = "update task set next_date = '" + next_date + "',state = 0 where id = " + id;
            //MessageBox.Show(sql);
            int rs = SQLiteHelper.ExecuteNonQuery(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);
            if (rs >= 0)
            {
                MainForm.instance.ReadMainLog("ID:" + id + "，标题：" + title + "任务修改下次执行时间：" + next_date);
            }
            else
            {
                MainForm.instance.ReadMainLog("ID:" + id + "，标题：" + title + "任务修改下次执行时间：" + next_date + "失败");
            }
        }
    }
}
